package com.education.admin.modules.community.controller;

import com.education.admin.common.Result;
import com.education.admin.modules.community.service.CommunityService;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;

import lombok.RequiredArgsConstructor;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * 小程序社区接口（前缀无 /api，避免形成 /api/api）
 */
@RestController
@RequestMapping({"/community","/api/community"})
@RequiredArgsConstructor
public class MiniCommunityController {

    private final CommunityService communityService;

    @GetMapping("/categories")
    public Result<List<Map<String, Object>>> categories() {
        // 前端已写死分类（问答、高分、经验），返回固定数据
        List<Map<String, Object>> categories = new ArrayList<>();
        
        String[] categoryNames = {"问答", "高分", "经验"};
        for (int i = 0; i < categoryNames.length; i++) {
            Map<String, Object> category = new HashMap<>();
            category.put("id", i + 1);
            category.put("name", categoryNames[i]);
            category.put("categoryName", categoryNames[i]);
            category.put("description", categoryNames[i] + "相关内容");
            category.put("postCount", 0);
            category.put("status", 1);
            categories.add(category);
        }
        
        return Result.success(categories);
    }

    @PostMapping("/posts/list")
    public Result<PageInfo<Map<String, Object>>> list(@RequestBody Map<String, Object> params) {
        String keyword = params.get("keyword") == null ? null : String.valueOf(params.get("keyword"));
        Long categoryId = null;
        if (params.get("categoryId") != null && !String.valueOf(params.get("categoryId")).isEmpty()) {
            try { categoryId = Long.parseLong(String.valueOf(params.get("categoryId"))); } catch (Exception ignored) {}
        }
        int pageNum = params.get("pageNum") == null ? 1 : Integer.parseInt(String.valueOf(params.get("pageNum")));
        int pageSize = params.get("pageSize") == null ? 10 : Integer.parseInt(String.valueOf(params.get("pageSize")));
        return Result.success(communityService.pagePosts(keyword, categoryId, pageNum, pageSize));
    }

    @GetMapping("/posts/{id}")
    public Result<Map<String, Object>> detail(@PathVariable Long id,
                                              @RequestParam(required = false) Long userId) {
        communityService.addView(id);
        if (userId != null) {
            return Result.success(communityService.getPostDetail(id, userId));
        }
        return Result.success(communityService.getPostDetail(id));
    }

    @GetMapping("/statistics")
    public Result<Map<String, Object>> statistics() {
        return Result.success(communityService.getStatistics());
    }

    @PostMapping("/posts")
    public Result<Map<String, Object>> create(@RequestBody Map<String, Object> post) {
        Long id = communityService.createPost(post);
        return Result.success(Map.of("id", id));
    }

    @PostMapping("/posts/{id}/like")
    public Result<Map<String, Object>> like(@PathVariable Long id, @RequestBody(required = false) Map<String, Object> body) {
        Long userId = body != null && body.get("userId") != null ? Long.valueOf(String.valueOf(body.get("userId"))) : 0L;
        String userType = body != null && body.get("userType") != null ? String.valueOf(body.get("userType")) : "student";
        boolean liked = communityService.toggleLike(id, userId, userType);
        return Result.success(Map.of("liked", liked));
    }

    @DeleteMapping("/posts/{id}")
    public Result<Void> delete(@PathVariable Long id) {
        communityService.deletePost(id);
        return Result.success();
    }

    // comments
    @GetMapping("/posts/{postId}/comments")
    public Result<Map<String, Object>> listComments(
            @PathVariable Long postId,
            @RequestParam(required = false) Long parentId,
            @RequestParam(required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) Long userId,
            @RequestParam(required = false) String userType) {
        
        // 如果传入了userId，使用带点赞状态的查询
        if (userId != null && userId > 0 && userType != null) {
            if (parentId != null) {
                var pi = communityService.pageRepliesWithLikeStatus(postId, parentId, pageNum, pageSize, userId, userType);
                return Result.success(Map.of("list", pi.getList(), "total", pi.getTotal(), "pageNum", pi.getPageNum(), "pageSize", pi.getPageSize()));
            }
            var pi = communityService.pageCommentsWithLikeStatus(postId, pageNum, pageSize, userId, userType);
            return Result.success(Map.of("list", pi.getList(), "total", pi.getTotal(), "pageNum", pi.getPageNum(), "pageSize", pi.getPageSize()));
        }
        
        // 否则使用原有的查询（不包含点赞状态）
        if (parentId != null) {
            var pi = communityService.pageReplies(postId, parentId, pageNum, pageSize);
            return Result.success(Map.of("list", pi.getList(), "total", pi.getTotal(), "pageNum", pi.getPageNum(), "pageSize", pi.getPageSize()));
        }
        var pi = communityService.pageComments(postId, pageNum, pageSize);
        return Result.success(Map.of("list", pi.getList(), "total", pi.getTotal(), "pageNum", pi.getPageNum(), "pageSize", pi.getPageSize()));
    }

    @PostMapping("/posts/{postId}/comments")
    public Result<Map<String, Object>> addComment(@PathVariable Long postId, @RequestBody Map<String, Object> body) {
        body.put("postId", postId);
        Long id = communityService.addComment(body);
        return Result.success(Map.of("id", id));
    }

    @DeleteMapping("/comments/{id}")
    public Result<Void> deleteComment(@PathVariable Long id, @RequestParam Long postId) {
        communityService.deleteComment(id, postId);
        return Result.success();
    }

    @PostMapping("/comments/{id}/like")
    public Result<Map<String, Object>> likeComment(@PathVariable Long id, @RequestBody(required = false) Map<String, Object> body) {
        Long userId = body != null && body.get("userId") != null ? Long.valueOf(String.valueOf(body.get("userId"))) : 0L;
        String userType = body != null && body.get("userType") != null ? String.valueOf(body.get("userType")) : "student";
        boolean liked = communityService.toggleCommentLike(id, userId, userType);
        return Result.success(Map.of("liked", liked));
    }

    // top resources for download block
    @GetMapping("/resources/top")
    public Result<List<Map<String, Object>>> topResources(@RequestParam(defaultValue = "2") Integer limit) {
        return Result.success(communityService.listTopResources(limit == null ? 2 : limit));
    }

    // posts with subject + subtype filters
    @GetMapping("/posts/filter")
    public Result<Map<String, Object>> filterPosts(@RequestParam(required = false) Long subjectId,
                                                   @RequestParam(required = false) String subType,
                                                   @RequestParam(required = false) String keyword,
                                                   @RequestParam(required = false) Long categoryId,
                                                   @RequestParam(required = false) Long userId,
                                                   @RequestParam(required = false) String userType,
                                                   @RequestParam(defaultValue = "1") int pageNum,
                                                   @RequestParam(defaultValue = "10") int pageSize) {
        String resolvedUserType = (userType == null || userType.isEmpty()) ? "student" : userType;
        var pi = communityService.pagePostsFiltered(subjectId, subType, keyword, categoryId, userId, resolvedUserType, pageNum, pageSize);
        return Result.success(Map.of("list", pi.getList(), "total", pi.getTotal(), "pageNum", pi.getPageNum(), "pageSize", pi.getPageSize()));
    }

    // following teachers' resources
    @GetMapping("/resources/following")
    public Result<List<Map<String, Object>>> followingResources(@RequestParam Long studentId, @RequestParam(defaultValue = "6") Integer limit){
        return Result.success(communityService.listFollowingResources(studentId, limit==null?6:limit));
    }

    // resource list page
    @GetMapping("/resources")
    public Result<Map<String, Object>> resources(@RequestParam(required = false) String keyword,
                                                 @RequestParam(required = false) String fileType,
                                                 @RequestParam(defaultValue = "1") int pageNum,
                                                 @RequestParam(defaultValue = "10") int pageSize){
        var pi = communityService.pageResources(keyword, fileType, pageNum, pageSize);
        return Result.success(Map.of("list", pi.getList(), "total", pi.getTotal(), "pageNum", pi.getPageNum(), "pageSize", pi.getPageSize()));
    }

    @PostMapping("/resources/{id}/download")
    public Result<Void> resourceDownload(@PathVariable Long id){
        communityService.addResourceDownload(id);
        return Result.success();
    }
}


